<template>
  <div class="attendance-container">
    <h2>员工年月考勤列表</h2>
    <!-- 筛选栏 -->
    <div class="filter-container">
      <label>年份：</label>
      <select v-model="selectedYear" class="filter-select">
        <option v-for="year in uniqueYears" :value="year" :key="year">
          {{ year }}
        </option>
      </select>
    </div>
    <button @click="showAddModal = true" class="add-button">添加考勤记录</button>

    <table class="attendance-table">
      <thead>
        <tr>
          <th>缺勤天数</th>
          <th>考勤金额</th>
          <th>年月份</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in paginatedList" :key="record.atd_id">
          <td>{{ record.atd_absentdays }}</td>
          <td>{{ record.atd_money }}</td>
          <td>{{ formatDate(record.atd_date) }}</td>
          <td>
            <button @click="editRecord(record)" class="edit-button">修改</button>
            <button @click="deleteRecord(record.atd_id)" class="delete-button">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 优化后的分页导航 -->
    <div class="pagination-container">
      <div class="total-count">
        共 {{ totalRecords }} 条记录，分 {{ totalPages }} 页显示
      </div>
      <div class="pagination-numbers">
        <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">
          <i class="fa fa-angle-left"> </i> &lt;&lt;
        </button>
        <template v-if="totalPages > 1">
          <button 
            @click="currentPage = 1"
            class="pagination-number"
            :class="{ 'active': currentPage === 1 }"
          >
            1
          </button>
          <span v-if="currentPage > 4" class="pagination-ellipsis">...</span>
          <button
            v-for="page in getDisplayedPages"
            :key="page"
            @click="currentPage = page"
            class="pagination-number"
            :class="{ 'active': currentPage === page }"
          >
            {{ page }}
          </button>
          <span v-if="currentPage < totalPages - 3" class="pagination-ellipsis">...</span>
          <button 
            @click="currentPage = totalPages"
            class="pagination-number"
            :class="{ 'active': currentPage === totalPages }"
          >
            {{ totalPages }}
          </button>
        </template>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">
          &gt;&gt; <i class="fa fa-angle-right"></i>
        </button>
      </div>
    </div>

    <!-- 添加模态框 -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <h3>添加考勤记录</h3>
        <div class="form-group">
          <label>缺勤天数:</label>
          <input v-model.number="newRecord.atd_absentdays" type="number" step="0.5"/>
        </div>
        <div class="form-group">
          <label>考勤金额:</label>
          <input v-model.number="newRecord.atd_money" type="number" step="0.01" />
        </div>
        <div class="form-group">
          <label>年月份:</label>
          <el-date-picker
            v-model="newRecord.atd_date"
            type="month"
            @change="newRecord.atd_date = formatToFullDate(newRecord.atd_date)"
            placeholder="Pick a month"
            style="width: 100%;"
          />
        </div>
        <div class="button-group">
          <button @click="addRecord" class="save-button">保存</button>
          <button @click="showAddModal = false" class="cancel-button">取消</button>
        </div>
      </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal">
      <div class="modal-content">
        <h3>编辑考勤记录</h3>
        <div class="form-group">
          <label>缺勤天数:</label>
          <input v-model.number="editedRecord.atd_absentdays" type="number" step="0.5"/>
        </div>
        <div class="form-group">
          <label>考勤金额:</label>
          <input v-model.number="editedRecord.atd_money" type="number" step="100" />
        </div>
        <div class="form-group">
          <label>年月份:</label>
          <el-date-picker
            v-model="editedRecord.atd_date"
            type="month"
            @change="editedRecord.atd_date = formatToFullDate(editedRecord.atd_date)"
            placeholder="Pick a month"
            style="width: 100%;"
          />
        </div>
        <div class="button-group">
          <button @click="updateRecord" class="save-button">保存</button>
          <button @click="showEditModal = false" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios from '../axios/index.js'
const value = ref('')
export default {
    props: {
        userId: {
            type: Number,
            required: true
        },
    },
    data() {
        return {
            selectedYear: new Date().getFullYear(),
            attendanceList: [],
            showAddModal: false,
            showEditModal: false,
            newRecord: { atd_absentdays: 0, atd_money: 0, atd_date: '' },
            editedRecord: { atd_id: null, atd_absentdays: 0, atd_money: 0, atd_date: '' },
            // 分页相关数据
            currentPage: 1,
            pageSize: 3, // 每页显示条数
            totalRecords: 0,
            totalPages: 1
        };
    },
    watch: {
        // 监听筛选年份变化，重新计算分页
        selectedYear() {
            this.currentPage = 1; // 重置为第一页
            this.calculatePagination();
        },
        
        // 监听数据变化，重新计算分页
        attendanceList() {
            this.calculatePagination();
        },
        'newRecord.atd_absentdays'(newValue) {
            if (newValue < 0) {
                this.newRecord.atd_absentdays = 0;
            }
        },
        'editedRecord.atd_absentdays'(newValue) {
            if (newValue < 0) {
                this.editedRecord.atd_absentdays = 0;
            }
        },
         userId(newVal) {
            if (newVal !== 0) {
                console.log('userId updated in child:', newVal);
                this.fetchAttendanceData();
            }
        }
    },
    computed: {
        filteredList() {
          return this.attendanceList.filter(record => {
            const recordYear = new Date(record.atd_date).getFullYear();
            return recordYear === this.selectedYear;
          });
        },

        paginatedList() {
          const start = (this.currentPage - 1) * this.pageSize;
          const end = start + this.pageSize;
          return this.filteredList.slice(start, end);
        },

        totalRecords() {
          return this.filteredList.length;
        },
        
        uniqueYears() {
          const years = this.attendanceList.map(record => 
            new Date(record.atd_date).getFullYear()
          );
          return [...new Set(years)].sort((a, b) => b - a);
        },
        getDisplayedPages() {
            return this.calculateDisplayedPages();
        }
    },
    mounted() {
        this.calculatePagination();
        this.fetchAttendanceData();
    },
    methods: { 
        formatDate(date) {
          if (date) {
            const d = new Date(date);
            return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
          }
          return '';
        },

        formatToFullDate(date) {
            if (date) {
                // 若输入为 Date 对象，转换为 YYYY-MM-DD
                if (date instanceof Date) {
                    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
                }
                // 若输入为 YYYY-MM，补全为 YYYY-MM-01
                if (/^\d{4}-\d{2}$/.test(date)) {
                    return `${date}-01`;
                }
                // 若输入为 ISO 8601 格式，转换为 YYYY-MM-DD
                if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(date)) {
                    const d = new Date(date);
                    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
                }
                return date;
            }
            return '';
        },
        calculatePagination() {
            this.totalRecords = this.filteredList.length;
            this.totalPages = Math.ceil(this.totalRecords / this.pageSize);
        },
        calculateDisplayedPages() {
            let pages = [];
            if (this.totalPages <= 7) {
                pages = Array.from({ length: this.totalPages - 2 }, (_, i) => i + 2);
            } else if (this.currentPage <= 4) {
                pages = [2, 3, 4, 5, 6, 7];
            } else if (this.currentPage >= this.totalPages - 3) {
                pages = [this.totalPages - 6, this.totalPages - 5, this.totalPages - 4, this.totalPages - 3, this.totalPages - 2, this.totalPages - 1];
            } else {
                pages = [this.currentPage - 2, this.currentPage - 1, this.currentPage, this.currentPage + 1, this.currentPage + 2];
            }
            return pages;
        },
        prevPage() {
            if (this.currentPage > 1) this.currentPage--;
        },
        nextPage() {
            if (this.currentPage < this.totalPages) this.currentPage++;
        },
        async fetchAttendanceData() {
            if (!this.userId) {
                console.log('fetchAttendanceData: 用户ID为空，跳过获取');
                return;
            }
            try {
                console.log('fetchAttendanceData: 正在获取用户', this.userId, '的考勤数据');
                const response = await axios.get(`/staffInfo/${this.userId}`);
                console.log('fetchAttendanceData: API响应:', response);

                if (response.data && response.data.code === 2000) {
                    console.log('fetchAttendanceData: 获取考勤数据成功:', response.data.data);
                    this.attendanceList = response.data.data;
                } else {
                    console.error('fetchAttendanceData: 获取考勤数据失败:', response.data.msg);
                    alert('获取考勤数据失败：' + response.data.msg);
                }
                this.calculatePagination();
            } catch (error) {
                console.error('fetchAttendanceData: Error fetching attendance data:', error);
                alert('无法获取考勤数据，请稍后再试。');
            }
        },
        async addRecord() {
            // 检查是否选择了年月份
            if (!this.newRecord.atd_date) {
                alert('请选择年月份');
                return;
            }
            try {
                const formattedDate = this.formatToFullDate(this.newRecord.atd_date);
                const response = await axios.post(`/staffInfo/${this.userId}`, {
                    atd_absentdays: this.newRecord.atd_absentdays,
                    atd_money: this.newRecord.atd_money,
                    atd_date: formattedDate
                });
                if (response.data && response.data.code === 2000) {
                    this.fetchAttendanceData();
                    this.showAddModal = false;
                    this.newRecord = { atd_absentdays: 0, atd_money: 0, atd_date: '' };
                } else {
                    console.error('添加考勤记录失败:', response.data.msg);
                }
            } catch (error) {
                console.error('Error adding record:', error);
                alert('无法添加考勤记录，请稍后再试。');
            }
        },
        editRecord(record) {
            this.editedRecord = { ...record };
            this.showEditModal = true;
        },
        async updateRecord() {
            try {
                const formattedDate = this.formatToFullDate(this.editedRecord.atd_date);
                const response = await axios.put(`/staffInfo/${this.editedRecord.atd_id}`, {
                    atd_absentdays: this.editedRecord.atd_absentdays,
                    atd_money: this.editedRecord.atd_money,
                    atd_date: formattedDate
                });
                if (response.data && response.data.code === 2000) {
                    this.fetchAttendanceData();
                    this.showEditModal = false;
                } else {
                    console.error('更新考勤记录失败:', response.data.msg);
                }
            } catch (error) {
                console.error('Error updating record:', error);
                alert('无法更新考勤记录，请稍后再试。');
            }
        },
        async deleteRecord(id) {
            if (confirm('确定要删除这条记录吗？')) {
                try {
                    const response = await axios.delete(`/staffInfo/${id}`);
                    if (response.data && response.data.code === 2000) {
                        this.fetchAttendanceData();
                    } else {
                        console.error('删除考勤记录失败:', response.data.msg);
                    }
                } catch (error) {
                    console.error('Error deleting record:', error);
                    alert('无法删除考勤记录，请稍后再试。');
                }
            }
        }
    }
};
</script>

<style scoped>
.attendance-container {
    padding: 20px;
}
.pagination-container{
    display: flex;
    justify-content: space-between;
}
.total-count {
    margin-top: auto;
    margin-bottom: auto;
}
.add-button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-bottom: 15px;
}

.attendance-table {
    width: 100%;
    border-collapse: collapse;
}

.attendance-table th, .attendance-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.attendance-table th {
    background-color: #f2f2f2;
}

.edit-button, .delete-button {
    padding: 5px 10px;
    margin-right: 5px;
    cursor: pointer;
    border: none;
    border-radius: 3px;
}

.edit-button {
    background-color: #2196F3;
    color: white;
}

.delete-button {
    background-color: #f44336;
    color: white;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    width: 400px;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
}

.form-group input {
    width: 95%;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
}

.save-button, .cancel-button {
    padding: 8px 15px;
    margin-left: 10px;
    cursor: pointer;
    border: none;
    border-radius: 4px;
}

.save-button {
    background-color: #4CAF50;
    color: white;
}

.cancel-button {
    background-color: #f44336;
    color: white;
}
.pagination-number {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    background-color: white;
    color: #333;
    transition: background-color 0.3s;
}

.pagination-number.active {
    background-color: #2196F3;
    color: white;
    border-color: #2196F3;
    cursor: not-allowed;
}

.pagination-ellipsis {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #f8f9fa;
    color: #666;
    cursor: default;
}

/* 筛选栏样式 */
.filter-container {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

h2 {
  color: #007bff;
  margin-bottom: 20px;
}
</style>